import os
import sys
import argparse
import re
import json
import time
import threading

parser = argparse.ArgumentParser(prog='Packer', description='直播游戏打包工具', epilog='©XuDonghao 2024-10-22')

parser.add_argument('-i', '--input', type=str, help='Input Path 输入工程路径', metavar='', default='.', required=False)

parser.add_argument('-o', '--output', type=str, help='Output Path 输出工程路径', metavar='', default='.', required=False)

parser.add_argument('-f', '--file', type=str, help='File Name 输出文件名', metavar='', default='zhfz', required=False)

parser.add_argument('-v', '--version', action='version', version='%(prog) v1.0')

parser.add_argument('-p', '--platform', type=str, help='平台[win/mac/ios/android]', metavar='', default='win', required=False)

parser.add_argument('-c', '--channel', type=str, help='渠道', metavar='', default='ks', required=False)

parser.add_argument('-b', '--package_version', type=str, help='输出程序版本号', metavar='', required=False)

args = parser.parse_args()

ext_7z = "C:\\Program Files\\7-Zip\\7z.exe"
# 输出文件后缀
ext = {"win": ".zip","mac": ".zip", "ios": ".ipa", "android": ".apk"}
# 定义正则表达式
pattern = r'\d+\.\d+\.\d+'

input_path = ''
output_path = ''


def write_txt_config(config_path, version):
    with open(config_path, 'w') as f:
        f.write('\"version\": \"' + version + '\"')

def write_json_config(config_path, version):
    config = {}
    with open(config_path, 'r') as f:
        config = json.load(f)
        
    config['version'] = version
    with open(config_path, 'w') as f:
        json.dump(config, f, indent=4)

def circle_print(stop_event, total_time=0):
    list_circle = ["\\", "|", "/", "—"]
    for i in range(total_time * 4):
        if stop_event.is_set():
            break

        time.sleep(0.25)
        print("\r{}".format(list_circle[i % 4]), end="", flush=True)

def pack(input_path, output_path, file_name, ext_name, version, platform, channel):
    file_name = file_name + '_' + version + ext_name
    ext_input_path = input_path
    if not input_path.endswith('\\') and not input_path.endswith('/'):
        ext_input_path = input_path + '\\*'

    file_name = os.path.join(output_path, file_name)

    print('快手打包 v1.0')
    print('平台：' + platform)
    print('渠道：' + channel)
    print('输入路径：' + ext_input_path)
    print('输出文件：' + file_name)
    print('版本号：' + version)

    print("-" * 30)
    print("开始写入版本号...")
    write_txt_config(os.path.join(input_path,'ver.txt'), version)
    write_json_config(os.path.join(input_path,'ks_manifest.json'), version)
    print('写入版本号完成')
    print("-" * 30)

    print('开始打包...')
    print("-" * 30)
    
    #7z a A.zip '.\super html\*' -mcu=on -oc:\Doc
    command = f"\"{ext_7z}\" a {file_name} {ext_input_path} -mcu=on"
    print("cmd:" + command)
    out = os.popen(command)

    stop_event = threading.Event()
    thread = threading.Thread(target=circle_print, args=(stop_event, 600,))
    thread.start()

    print(out.read())
    stop_event.set()
    thread.join()

    print("-" * 30)
    print('打包完成')

if __name__ == '__main__':
    if not args.package_version or not re.search(pattern, args.package_version):
        print('程序版本号格式错误，正确格式为：1.0.0')
        parser.print_help()
        sys.exit(1)

    input_path = os.path.abspath(args.input)
    input_path = os.path.normpath(input_path)
    output_path = os.path.abspath(args.output)
    output_path = os.path.normpath(output_path)
    if not os.path.exists(input_path):
        print('输入路径不存在!')
        parser.print_help()
        sys.exit(1)

    if not os.path.exists(output_path):
        os.makedirs(output_path)

    if not args.platform in ext:
        print('平台错误!')
        parser.print_help()
        sys.exit(1)

    pack(input_path, output_path, args.file, ext[args.platform], args.package_version, args.platform, args.channel)

    input('Press Enter to exit...')